# coding=utf-8
from . import api
from flask import request, render_template, jsonify
from app import util, redis, aes_util
from dbConnection.MysqlConn import Mysql
from Crypto.Cipher import AES
import base64, time
import sys
reload(sys)
sys.setdefaultencoding('utf8')


@api.route('/api/scan_card', methods=['post', 'get'])
def scan_card_new():
    data = {}
    data['flag'] = 0
    data['code'] = 400
    try:
        card = request.values.get('card', '')
        machine = request.values.get('machineNum', '')
        r = request.values.get('r', default='0')
        s, v_time = time_code(str(machine), r)
        if s is False:
            data['code'] = 408  # 请求超时
            return util.to_json(data)
        card_str = base64.b64decode(card)
        card_str = card_str.encode('utf-8').strip()
        user = get_user_plate(card_str)
        rate_flag = redis.get(machine)
        if rate_flag:
            data['code'] = 405  # 洗车超出规定次数
            return util.to_json(data)
        if user is None:
            data['code'] = 401  # 车牌未绑定
            return util.to_json(data)
        user_info = get_user_info(user['uid'])
        if user_info is None or user_info['status'] == 0:
            data['code'] = 406  # 用户不存在或已锁定
            return util.to_json(data)
        jiqi = get_jiqi(machine)
        if jiqi is None:
            data['code'] = 402  # 机器编码错误
            return util.to_json(data)
        res = car_wash_num_detail(user['uid'])
        if res is None:
            data['code'] = 403  # 没有剩余洗车次数
            return util.to_json(data)
        content = update_user_wash(res['uid'], res['id'])
        if content > 0:
            redis.set(machine, '1', ex=1)
            data['flag'] = 1
            data['code'] = 200
            add_user_wash(res['uid'], res['id'], card_str, jiqi['machineId'], jiqi['storeId'])
    except Exception as e:
        print e
        data['code'] = 500
    return util.to_json(data)


# 新增用户洗车记录
def add_user_wash(uid, tid, plate, mid, sid):
    sql = "insert INTO car_wash(uid, machineId, storeId, plateNum, user_card, washTime) VALUES ('%s', '%s', '%s', " \
          "'%s', '%s', now())" % (uid, mid, sid, plate, tid)
    mysql = Mysql()
    mysql.insertOne(sql, None)
    mysql.dispose()


# 更新用户剩余洗车次数
def update_user_wash(uid, tid):
    sql = "update user_taocan SET use_num = use_num + 1 WHERE uid = '%s' AND id = '%s'" % (uid, tid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    return res


# 查询是否有洗车次数
def car_wash_num(uid):
    sql = "SELECT (sum(recharge_num) - sum(use_num)) wash_num from user_taocan where uid = '%s' and now() < end_time" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    num = int(res['wash_num']) if res['wash_num'] else 0
    return num


# 查询是否有洗车次数
def car_wash_num_detail(uid):
    sql = "SELECT * from user_taocan where uid = '%s' and end_time > now() and recharge_num > use_num ORDER BY" \
          " id asc limit 1 " % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 查询机器
def get_jiqi(machine):
    sql = "select * FROM car_machine WHERE machineNum = '%s'" % machine
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 查询车牌是否存在
def get_user_plate(card_str):
    sql = "select * FROM car_plate WHERE license_plate = '%s'" % card_str
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 洗车接口
# @api.route('/api/scan_card', methods=['post', 'get'])
# def scan_card():
#     data = {}
#     try:
#         card = request.values.get('card', default=' ')
#         print card
#         machine = request.values.get('machineNum', default=' ')
#         r = request.values.get('r', default='0')
#         s, v_time = time_code(str(machine), r)
#         if s is False:
#             data['code'] = 408  # 请求超时
#         else:
#             card_str = base64.b64decode(card)
#             card_str = card_str.encode('utf-8').strip()
#             sql = "select washNum, uid, status FROM car_users WHERE plateNum = '%s'" % card_str
#             mysql = Mysql()
#             res = mysql.getOne(sql, None)
#             mysql.dispose()
#             print sql
#             print res
#             print card_str
#             if res:
#                 if res['status'] == 0:
#                     data['code'] = 403  # 用户已禁用
#                 else:
#                     if int(res['washNum']) > 0:
#                         data['code'] = 200
#                         data['washNum'] = int(res['washNum']) - 1
#                         update_user_wash(res['uid'])  # 更新用户剩余洗车次数
#                         insert_wash_car(res['uid'], machine, card_str)  # 插入洗车记录
#                     else:
#                         cont = get_new_order(machine, v_time)
#                         if cont:
#                             data['code'] = 202
#                             data['washNum'] = 0  # 存在新的支付订单(不更新用户次数)
#                             insert_wash_car(cont['uid'], machine, card_str)  # 更新会员
#                             update_orders(cont['id'])
#                         else:
#                             data['code'] = 400  # 没有洗车次数
#             else:
#                 cont = get_new_order(machine, v_time)
#                 if cont:
#                     data['code'] = 201
#                     data['washNum'] = 0  # 存在新的支付订单(不更新用户次数)
#                     insert_wash_car(cont['uid'], machine, card_str)  # 更新游客
#                     update_orders(cont['id'])
#                 else:
#                     data['code'] = 401  # 没有新订单
#     except Exception as e:
#         print e
#         data['code'] = 500
#     print data
#     return util.to_json(data)


# 获取服务器当前时间
@api.route('/api/get_new_time', methods=['get', 'post'])
def get_new_time():
    data = {}
    try:
        data['now_time'] = int(time.time())
        data['code'] = 200
    except Exception as e:
        print e
        data['code'] = 500
    return util.to_json(data)


# 会员查询接口
@api.route('/api/get_user', methods=['post', 'get'])
def get_user():
    data = {}
    data['user_flag'] = 0
    data['washNum'] = 0
    data['orderid'] = "None"
    try:
        card = request.values.get('card', default=' ')
        print card
        machine = request.values.get('machineNum', default=' ')
        r = request.values.get('r', default='0')
        s, v_time = time_code(str(machine), r)
        if s is False:
            data['code'] = 408  # 请求超时
            return util.to_json(data)
        card_str = base64.b64decode(card)
        card_str = card_str.encode('utf-8').strip()
        user = get_user_plate(card_str)
        if user is None:
            data['code'] = 401  # 车牌未绑定
            return util.to_json(data)
        user_info = get_user_info(user['uid'])
        if user_info is None or user_info['status'] == 0:
            data['code'] = 406  # 用户不存在或已锁定
            return util.to_json(data)
        jiqi = get_jiqi(machine)
        if jiqi is None:
            data['code'] = 402  # 机器编码错误
            return util.to_json(data)
        res = car_wash_num_detail(user['uid'])
        if res < 1:
            data['code'] = 403  # 没有剩余洗车次数
            return util.to_json(data)
        data['code'] = 200
        data['user_flag'] = 1
        data['washNum'] = car_wash_num(user['uid'])
    except Exception as e:
        print e
        data['code'] = 500
    return util.to_json(data)


# 验证时间是否有效
def time_code(machine, time_str):
    flag = True
    s_time = 0
    try:
        s = aes_util.AES_ENCRYPT(str(machine).strip())
        crs = time_str.replace(' ', '+')
        v_time = s.decrypt(crs)
        now_time = int(time.time())
        v_str = str(v_time).encode('utf-8')
        print v_str
        print len(v_str)
        if now_time - int(v_str[:10]) > 300:
            flag = False
            # s_time = int(v_str[:10])
        else:
            s_time = int(v_str[:10])
    except Exception as e:
        print e
        flag = False
    return flag, s_time


# 查询用户信息
def get_user_info(uid):
    sql = "select * FROM car_users WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# # 查询机器是否有订单
# def get_new_order(machine, v_time):
#     pay_time = int(v_time) - 7200
#     sql = "select c.* FROM car_orders as c LEFT JOIN car_machine as m on m.machineId = c.machineId WHERE c.orderType = 0 " \
#           "AND unix_timestamp(c.payTime) > '%s' AND m.machineNum = '%s'" % (pay_time, machine)
#     mysql = Mysql()
#     res = mysql.getOne(sql, None)
#     mysql.dispose()
#     print sql
#     print res
#     return res
#
#
# # 更新订单状态
# def update_orders(uid):
#     mysql = Mysql()
#     try:
#         sql = "update car_orders SET orderType = 1 WHERE id = '%s'" % uid
#         mysql.update(sql, None)
#     except Exception as e:
#         print e
#     mysql.dispose()
#
#
# # 添加洗车记录
# def insert_wash_car(uid, machine, card):
#     machineId = 0
#     storeId = 0
#     mid = redis.hget('all_machine_conf', str(machine))
#     if mid:
#         con = eval(mid)
#         machineId = con['machineId']
#         storeId = con['storeId']
#     sql = "insert INTO car_wash(uid, machineId, storeId, plateNum, washTime) VALUES ('%s', '%s', '%s', '%s', now())" \
#           % (uid, machineId, storeId, card)
#     mysql = Mysql()
#     mysql.insertOne(sql, None)
#     mysql.dispose()


# # 更新用户剩余洗车次数
# def update_user_wash(uid):
#     sql = "update car_users SET washNum = washNum - 1 WHERE uid = '%s'" % uid
#     mysql = Mysql()
#     mysql.update(sql, None)
#     mysql.dispose()
